package com.jianggy.nio;

import org.apache.hadoop.hbase.nio.ByteBuff;
import org.glassfish.jersey.message.internal.StringBuilderUtils;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 *写入csv数据
 *@author jianggy
 *@date 2023/3/6
 *@version 1.0
 **/
public class WriteCsv {
    public static void main(String[] args) throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile("C:\\Users\\admin\\Desktop\\test1.csv", "rw");
        FileChannel channel = randomAccessFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(102400);
        byte[] header = ("id," + "register," + "age," + "gender," + "property," + "debt" + "\n").getBytes();
        buffer.put(header);
        buffer.flip();
        channel.write(buffer);
        buffer.clear();
        LocalDateTime localDateTime = LocalDateTime.of(1970, 1, 1, 0, 0, 0);
        for (int i = 0; i < 100; i++) {
            for (int j = 1; j <= 10; j++) {
                StringBuilder stringBuilder = new StringBuilder();
                //身份证
                stringBuilder.append(CertUtils.fakeId()).append(",");
                //时间
                localDateTime = localDateTime.plus(1, ChronoUnit.MINUTES);
                stringBuilder.append(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append(",");
                //年龄
                stringBuilder.append(ThreadLocalRandom.current().nextInt(100)).append(",");
                //性别
                stringBuilder.append(j%2).append(",");
                //财富
                stringBuilder.append(ThreadLocalRandom.current().nextInt(1000000)).append(",");
                //负债
                stringBuilder.append(ThreadLocalRandom.current().nextInt(10000000));
                stringBuilder.append("\n");
                System.out.println(stringBuilder.toString());
                buffer.put(stringBuilder.toString().getBytes());
            }
            buffer.flip();
            channel.write(buffer);
            buffer.clear();
        }
        channel.close();
    }
}
